//
//  BaseViewController.m
//  ETONEQP
//
//  Created by Lin Zhang on 2018/9/4.
//  Copyright © 2018年 Lin Zhang. All rights reserved.


#import "BaseViewController.h"
#import <MBProgressHUD.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
//定位服务
#import <CoreLocation/CoreLocation.h>

@interface BaseViewController ()<CLLocationManagerDelegate>

@property(nonatomic,strong) CLLocationManager* locationManager;
@property(nonatomic,assign) BOOL hasLocation;
@property(nonatomic,strong) NSString* longitude;
@property(nonatomic,strong) NSString* latitude;

@property(nonatomic,strong) MBProgressHUD* progressTipsView;
@property(nonatomic,strong) MBProgressHUD* resultTipsView;

@end

@implementation BaseViewController

@synthesize locationManager;
@synthesize hasLocation;
@synthesize longitude;
@synthesize latitude;
@synthesize progressTipsView;
@synthesize resultTipsView;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //设置导航栏透明
//    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //过程
    if (progressTipsView == nil) {
        progressTipsView = [[MBProgressHUD alloc] initWithView:[self view]];
        progressTipsView.bezelView.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:0.7];
        progressTipsView.contentColor = [UIColor whiteColor];
        progressTipsView.detailsLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16.0f];
        [progressTipsView setMode:MBProgressHUDModeIndeterminate];
    }
    
    //成功或失败提示
    if (resultTipsView==nil) {
        resultTipsView = [[MBProgressHUD alloc] initWithView:[self view]];
        resultTipsView.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        resultTipsView.bezelView.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:0.7];
        resultTipsView.animationType = MBProgressHUDAnimationZoom;
        resultTipsView.contentColor = [UIColor whiteColor];
        resultTipsView.detailsLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16.0f];
        [resultTipsView setMode:MBProgressHUDModeCustomView];
        [resultTipsView hideAnimated:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)showSuccessResultTips:(NSString*)resultMsg animated:(BOOL)animated{
    UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toast_icon_sueesee"]];
    resultTipsView.customView = imageView;
    resultTipsView.detailsLabel.text = resultMsg;
    [[[self view] window] addSubview:resultTipsView];
    [resultTipsView showAnimated:YES];
}

-(void)showFailedResultTips:(NSString*)errorMsg animated:(BOOL)animated{
    UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toast_icon_fail"]];
    resultTipsView.customView = imageView;
    resultTipsView.detailsLabel.text = errorMsg;
    [[[self view] window] addSubview:resultTipsView];
    [resultTipsView showAnimated:YES];
}

-(void)showSuccessResultTips:(NSString*)resultMsg animated:(BOOL)animated forSeconds:(NSTimeInterval)seconds{
    [self showSuccessResultTips:resultMsg animated:animated forSeconds:seconds completionBlock:^{
        
    }];
}

-(void)showFailedResultTips:(NSString*)errorMsg animated:(BOOL)animated forSeconds:(NSTimeInterval)seconds{
    [self showFailedResultTips:errorMsg animated:animated forSeconds:seconds completionBlock:^{
        
    }];
}

-(void)showSuccessResultTips:(NSString *)resultMsg animated:(BOOL)animated forSeconds:(NSTimeInterval)seconds completionBlock:(ShowCompletionBlock)completion{
    UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toast_icon_sueesee"]];
    resultTipsView.customView = imageView;
    //resultTipsView.label.text = resultMsg;
    resultTipsView.detailsLabel.text = resultMsg;
    [[[self view] window] addSubview:resultTipsView];
    [resultTipsView showAnimated:YES];
    
    
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        float progress = 0.0f;
        while (progress < 1.0f) {
            progress += 0.01f;
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD HUDForView:self.view].progress = progress;
            });
            usleep(seconds * 10000);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //[self->resultTipsView hideAnimated:YES];
            [self->resultTipsView removeFromSuperview];
            completion();
        });
    });
}

-(void)showFailedResultTips:(NSString*)errorMsg animated:(BOOL)animated forSeconds:(NSTimeInterval)seconds completionBlock:(ShowCompletionBlock)completion{
    UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    resultTipsView.customView = imageView;
    resultTipsView.detailsLabel.text = errorMsg;
    [[[self view] window] addSubview:self->resultTipsView];
    [resultTipsView showAnimated:YES];
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        float progress = 0.0f;
        while (progress < 1.0f) {
            progress += 0.01f;
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD HUDForView:self.view].progress = progress;
            });
            usleep(seconds * 10000);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->resultTipsView removeFromSuperview];
            completion();
        });
    });
}

//增加方法  失败信息提示展示图片
-(void)showFailedResultTipsWithImage:(NSString*)errorMsg animated:(BOOL)animated forSeconds:(NSTimeInterval)seconds completionBlock:(ShowCompletionBlock)completion{
    UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toast_icon_fail"]];
    resultTipsView.customView = imageView;
    resultTipsView.detailsLabel.text = errorMsg;
    [[[self view] window] addSubview:self->resultTipsView];
    [resultTipsView showAnimated:YES];
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        float progress = 0.0f;
        while (progress < 1.0f) {
            progress += 0.01f;
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD HUDForView:self.view].progress = progress;
            });
            usleep(seconds * 10000);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->resultTipsView removeFromSuperview];
            completion();
        });
    });
}




-(void)hideResultTips:(BOOL)animated{
    [resultTipsView hideAnimated:YES];
    [resultTipsView removeFromSuperview];
}

-(void)showProgressTips:(NSString*)progressMsg animated:(BOOL)animated{
    progressTipsView.label.text = progressMsg;
    [[[self view] window] addSubview:progressTipsView];
    [progressTipsView showAnimated:YES];
}

-(void)hideProgressTips:(BOOL)animated{
    [progressTipsView hideAnimated:YES];
    [progressTipsView removeFromSuperview];
    
}

-(NSMutableAttributedString *)gettextStyle:(NSString *)fontName font:(float)font color:(UIColor *)color text:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] =color;
    textAttrs[NSFontAttributeName] = [UIFont fontWithName:fontName size:font];
    return attributedString;
}

-(void)startLocation{
    locationManager = [[CLLocationManager alloc]init];
    hasLocation = NO;
    if ( [CLLocationManager locationServicesEnabled]) {
        [[self locationManager] setDelegate:self];
        [[self locationManager] setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
        //授权
        if ([[self locationManager] respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            
            [[self locationManager] requestWhenInUseAuthorization];
        }
        [[self locationManager] startUpdatingLocation];
    }else{
        [self showFailedResultTips:@"请打开设置、隐私、定位服务" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
    }
}

#pragma mark - CLLocationManagerDelegate
//定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    if (![self hasLocation]) {
        CLLocation *currentLocation = [locations lastObject];
        if (currentLocation!=nil) {
            CLLocationCoordinate2D coor = currentLocation.coordinate;
            latitude = [NSString stringWithFormat:@"%f",coor.latitude];
            longitude = [NSString stringWithFormat:@"%f",coor.longitude];
            CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
            [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (placemarks.count > 0) {
//                        CLPlacemark *placeMark = placemarks[0];
//                        self.cityName = placeMark.locality;
//                        [[NSUserDefaults standardUserDefaults] setObject:self.cityName forKey:@"cityName"];
//                        if (!placeMark.locality) {
//                            NSLog(@"获取城市失败");
//                        }
                    }
                });
                
            }];
            NSLog(@"经度:%@纬度:%@",longitude,latitude);            
            [[self locationManager] stopUpdatingLocation];
            self.hasLocation=YES;
        }
    }
}



//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *) error{
    NSString *errorString;
    [manager stopUpdatingLocation];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"cityName"];
    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
        {
            //Access denied by user
            errorString = @"Access to Location Services denied by user";
            //Do something...
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"您未授权获取地理位置信息,请授权后重启客户端!" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                exit(0);
            }];
            [alertVC addAction:okAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
            break;
        }
        case kCLErrorLocationUnknown:
        default:
            if (![self hasLocation]) {
                latitude = @"";
                longitude = @"";
                [[self locationManager] stopUpdatingLocation];
                self.hasLocation = YES;
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"您未授权获取地理位置信息,请授权后重启客户端!" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    exit(0);
                }];
                [alertVC addAction:okAction];
                [self presentViewController:alertVC animated:YES completion:nil];
            }
            break;
    }
}

//获取真实ip
-(NSString *)getRealIPAddress{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
    NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
    if ([ip hasPrefix:@"var returnCitySN = "]) {
    NSRange range = NSMakeRange(0, 19);
        [ip deleteCharactersInRange:range];
        NSString * nowIp =[ip substringToIndex:ip.length-1];
        NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        return dict[@"cip"] ? dict[@"cip"] : @"";
        
    }
        return @"";
    
}
// 获取设备IP地址
-(NSString *)getLocalIPAddress{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // 检索当前接口,在成功时,返回0
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // 循环链表的接口
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // 检查接口是否en0 wifi连接在iPhone上
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // 得到NSString从C字符串
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // 释放内存
    freeifaddrs(interfaces);
    return address;
}


@end
